<template>
  <el-card 
    :title="`${website.name} 业务闭环检测`"
    class="business-loop-card"
    style="margin-top: 24px"
    v-if="website"
  >
    <template #extra>
      <el-space>
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button @click="handleRefresh" :loading="isLoading">
          刷新
        </el-button>
      </el-space>
    </template>

    <div v-loading="isLoading">
      <!-- 错误提示 -->
      <el-alert
        v-if="error"
        :title="error"
        type="error"
        :closable="false"
        style="margin-bottom: 16px"
      />

      <!-- 完整性统计 -->
      <el-row :gutter="16" v-if="businessLoopIntegrity" style="margin-bottom: 24px">
        <el-col :xs="24" :sm="8" v-for="(stat, index) in integrityStats" :key="index">
          <el-card class="stats-card">
            <el-statistic
              :title="stat.title"
              :value="stat.value"
              :value-style="stat.valueStyle"
            >
              <template #prefix>
                <el-icon :style="{ color: stat.valueStyle.color }" :size="24">
                  <component :is="stat.icon" />
                </el-icon>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>

      <!-- 缺失步骤警告 -->
      <el-alert
        v-if="businessLoopIntegrity?.missingSteps?.length > 0"
        :title="`业务闭环不完整，缺失步骤: ${businessLoopIntegrity.missingSteps.join(', ')}`"
        type="warning"
        :closable="false"
        style="margin-bottom: 16px"
      />

      <!-- 业务闭环记录表格 -->
      <el-table
        :data="displayRecords"
        style="width: 100%"
        :row-key="(row: any) => `${row.timestamp}-${row.step}`"
        v-if="displayRecords && displayRecords.length > 0"
      >
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.timestamp).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="step" label="步骤" width="150">
          <template #default="{ row }">
            {{ STEP_NAMES[row.step] || row.step }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-space>
              <el-icon :color="getStatusColor(row.status)">
                <component :is="getStatusIcon(row.status)" />
              </el-icon>
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="消息" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="120">
          <template #default="{ row }">
            {{ row.ip === 'N/A' ? '-' : row.ip }}
          </template>
        </el-table-column>
        <el-table-column prop="sessionId" label="会话ID" width="200" show-overflow-tooltip />
      </el-table>
      
      <!-- 无数据提示 -->
      <el-empty 
        v-else
        description="暂无业务闭环记录"
        style="padding: 50px"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useTrackingStore } from '@/store/tracking'
import { Check, CircleClose, Clock, Warning } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

interface Website {
  id: string | number
  name: string
}

interface Props {
  website?: Website | null
}

const props = defineProps<Props>()

const trackingStore = useTrackingStore()
// 使用 storeToRefs 保持响应式
const { businessLoopLogs, businessLoopIntegrity, error } = storeToRefs(trackingStore)
const { fetchBusinessLoopLogs, checkBusinessLoopIntegrity } = trackingStore

// 本地加载状态
const isLoading = ref(false)
const selectedDate = ref(dayjs().format('YYYY-MM-DD'))

// 显示的业务闭环记录：优先使用 businessLoopIntegrity.records，其次使用 businessLoopLogs
const displayRecords = computed(() => {
  const integrity = businessLoopIntegrity.value
  if (integrity?.records && Array.isArray(integrity.records) && integrity.records.length > 0) {
    return integrity.records
  }
  if (businessLoopLogs.value && Array.isArray(businessLoopLogs.value) && businessLoopLogs.value.length > 0) {
    return businessLoopLogs.value
  }
  return []
})

const STEP_NAMES: Record<string, string> = {
  'SCRIPT_LOADED': '脚本加载',
  'PAGEVIEW_SENT': '数据发送',
  'PAGEVIEW_RECEIVED': '服务器接收',
  'PAGEVIEW_SAVED': '数据保存',
  'ERROR': '错误'
}

const getStatusIcon = (status: string) => {
  const iconMap: Record<string, any> = {
    'SUCCESS': Check,
    'FAILED': CircleClose,
    'PENDING': Clock,
    'DEFAULT': Warning
  }
  return iconMap[status] || Warning
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'SUCCESS': '#67C23A',
    'FAILED': '#F56C6C',
    'PENDING': '#E6A23C',
    'DEFAULT': '#909399'
  }
  return colorMap[status] || '#909399'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'SUCCESS': '成功',
    'FAILED': '失败',
    'PENDING': '等待中',
    'DEFAULT': '未知'
  }
  return textMap[status] || '未知'
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'PENDING': 'warning',
    'DEFAULT': 'info'
  }
  return typeMap[status] || 'info'
}

const integrityStats = computed(() => {
  const integrity = businessLoopIntegrity.value
  if (!integrity) {
    return [
      { title: '完整性状态', value: '未知', valueStyle: { color: '#909399' }, icon: Warning },
      { title: '总步骤数', value: 0, valueStyle: { color: '#409EFF' }, icon: Check },
      { title: '缺失步骤', value: 0, valueStyle: { color: '#E6A23C' }, icon: Warning }
    ]
  }
  
  return [
    {
      title: '完整性状态',
      value: integrity.isComplete ? '完整' : '不完整',
      valueStyle: { 
        color: integrity.isComplete ? '#67C23A' : '#F56C6C' 
      },
      icon: integrity.isComplete ? Check : CircleClose
    },
    {
      title: '总步骤数',
      // 使用 totalSteps 或 records.length
      value: integrity.totalSteps ?? (integrity.records?.length || 0),
      valueStyle: { color: '#409EFF' },
      icon: Check
    },
    {
      title: '缺失步骤',
      value: integrity.missingSteps?.length || 0,
      valueStyle: { color: '#E6A23C' },
      icon: Warning
    }
  ]
})

const handleDateChange = () => {
  if (props.website) {
    fetchData()
  }
}

const handleRefresh = () => {
  fetchData()
}

const fetchData = async () => {
  if (!props.website || !props.website.trackingId) return
  
  isLoading.value = true
  try {
    // 业务闭环 API 需要使用 trackingId 而不是 website.id
    await Promise.all([
      fetchBusinessLoopLogs(props.website.trackingId, selectedDate.value),
      checkBusinessLoopIntegrity(props.website.trackingId, selectedDate.value)
    ])
  } catch (err: any) {
    console.error('获取业务闭环数据失败:', err)
  } finally {
    isLoading.value = false
  }
}

watch(() => props.website, () => {
  if (props.website) {
    fetchData()
  }
}, { immediate: true })

watch(selectedDate, () => {
  if (props.website) {
    fetchData()
  }
})
</script>

<style scoped lang="scss">
.business-loop-card {
  border-radius: 8px;
}

.stats-card {
  text-align: center;
}
</style>

